<template>
  <div>
    <div class="front-notice"><el-icon><Bell /></el-icon>公告：{{ data.top }}</div>
    <div class="front-header">
      <div class="front-header-left">
        <img src="@/assets/imgs/logo.png" alt="">
        <a href="/front/home"><div class="title">在线图书管理系统</div></a>
      </div>
      <div class="front-header-center">
        <el-menu :default-active="router.currentRoute.value.path" router mode="horizontal">
          <el-menu-item index="/front/home">首页</el-menu-item>
          <el-menu-item index="/front/posts">图书社区</el-menu-item>
          <el-menu-item index="/front/activity">图书活动</el-menu-item>
          <el-menu-item index="/front/room">阅览室</el-menu-item>
          <el-menu-item index="/front/book">图书馆</el-menu-item>
        </el-menu>
      </div>
      <div style="width: 350px">
        <el-input clearable style="width: 240px; margin-right: 10px" v-model="data.name" placeholder="请输入图书名称搜索"></el-input>
        <el-button @click="goPage('/front/book?name=' + data.name)" type="primary">搜索</el-button>
      </div>
      <div class="front-header-right">
        <div v-if="!data.user.id">
          <el-button @click="login_open">登录</el-button>
          <el-button @click="register_open">注册</el-button>
        </div>
        <div v-else>
          <el-dropdown style="cursor: pointer; height: 60px">
            <div style="display: flex; align-items: center">
              <img style="width: 40px; height: 40px; border-radius: 50%;" :src="data.user.avatar" alt="">
              <span style="margin-left: 5px; color: #333">{{ data.user.name }}</span><el-icon><arrow-down /></el-icon>
            </div>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item @click="goPage('/front/cart')">我的书单</el-dropdown-item>
                <el-dropdown-item @click="goPage('/front/orders')">我的借书</el-dropdown-item>
                <el-dropdown-item @click="goPage('/front/myPosts')">我的发帖</el-dropdown-item>
                <el-dropdown-item @click="goPage('/front/sign')">我报名的活动</el-dropdown-item>
                <el-dropdown-item @click="goPage('/front/collect')">我收藏的活动</el-dropdown-item>
                <el-dropdown-item @click="goPage('/front/mySeatReserve')">我预约的座位</el-dropdown-item>
                <el-dropdown-item @click="goPage('/front/person')">个人信息</el-dropdown-item>
                <el-dropdown-item @click="goPage('/front/password')">修改密码</el-dropdown-item>
                <el-dropdown-item @click="logout">退出登录</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
      </div>
    </div>
    <div class="main-body">
      <RouterView @updateUser="updateUser" />
    </div>

    <Footer />

<!--  登录对话框  -->
    <el-dialog title="" v-model="data.open" width="400px" append-to-body>
      <el-form ref="formRef" :model="data.form" :rules="data.rules">
        <el-form-item prop="username">
          <el-input :prefix-icon="User" size="large" v-model="data.form.username" placeholder="请输入账号"></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input show-password :prefix-icon="Lock" size="large" v-model="data.form.password" placeholder="请输入密码"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button size="large" type="primary" style="width: 100%" @click="login">登 录</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

<!--  注册对话框  -->
    <el-dialog title="" v-model="data.show" width="400px" append-to-body>
      <el-form ref="formRefs" :model="data.forms" :rules="data.rule">
        <el-form-item prop="username">
          <el-input :prefix-icon="User" size="large" v-model="data.forms.username" placeholder="请输入账号"></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input show-password :prefix-icon="Lock" size="large" v-model="data.forms.password" placeholder="请输入密码"></el-input>
        </el-form-item>
        <el-form-item prop="confirmPassword">
          <el-input show-password :prefix-icon="Lock" size="large" v-model="data.forms.confirmPassword" placeholder="请确认密码"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button size="large" type="primary" style="width: 100%" @click="register">注 册</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script setup>
  import router from "@/router/index.js";
  import {reactive, ref} from "vue";
  import request from "@/utils/request.js";
  import Footer from "@/components/Footer.vue";
  import {ElMessage} from "element-plus";

  const validatePass = (rules, value, callback) => {
    if (!value) {
      callback(new Error('请确认密码'))
    } else {
      if (value !== data.forms.password) {
        callback(new Error("确认密码跟原密码不一致!"))
      }
      callback()
    }
  }

  const data = reactive({
    title: null,
    open: false,
    show: false,
    user: JSON.parse(localStorage.getItem('xm-user') || '{}'),
    top: '',
    noticeData: [],
    name: null,
    form: { role: 'USER' },
    rules: {
      username: [
        { required: true, message: '请输入账号', trigger: 'blur' }
      ],
      password: [
        { required: true, message: '请输入密码', trigger: 'blur' }
      ]
    },
    forms: { },
    rule: {
      username: [
        { required: true, message: '请输入账号', trigger: 'blur' }
      ],
      password: [
        { required: true, message: '请输入密码', trigger: 'blur' }
      ],
      confirmPassword: [
        { validator: validatePass, trigger: 'blur' }
      ]
    }
  })

  const goPage = (path) => {
    location.href = path
  }

  const logout = () => {
    localStorage.removeItem('xm-user')
    router.push('/')
    //刷新页面
    location.reload()
  }

  const updateUser = () => {
    data.user =  JSON.parse(localStorage.getItem('xm-user') || '{}')
  }

  const loadNotice = () => {
    request.get('/notice/selectAll').then(res => {
      data.noticeData = res.data
      let i = 0
      if (data.noticeData && data.noticeData.length) {
        data.top = data.noticeData[0].content
        setInterval(() => {
          data.top = data.noticeData[i].content
          i++
          if (i === data.noticeData.length) {
            i = 0
          }
        }, 2500)
      }
    })
  }

  const login_open = () => {
    data.open = true
  }

  const formRef = ref()
  const login = () => {
    formRef.value.validate(valid => {
      if (valid) { // 表示表单校验通过
        request.post('/login', data.form).then(res => {
          if (res.code === '200') {
            // 存储用户信息到浏览器的缓存
            localStorage.setItem('xm-user', JSON.stringify(res.data))
            ElMessage.success('登录成功')
            setTimeout(() => {
              location.href = '/front/home'
            }, 500)
          } else {
            ElMessage.error(res.msg)
          }
        })
      }
    })
  }

  const register_open = () => {
    data.show = true
  }

  const formRefs = ref()
  const register = () => {
    formRefs.value.validate(valid => {
      if (valid) { // 表示表单校验通过
        request.post('/register', data.forms).then(res => {
          if (res.code === '200') {
            ElMessage.success('注册成功')
            data.show = false
            /*router.push('/login')*/
          } else {
            ElMessage.error(res.msg)
          }
        })
      }
    })
  }
  loadNotice()
</script>

<style scoped>
@import "@/assets/css/front.css";
</style>
